<?php
class IOSS_Withdraw{
	private static $table = 'core_withdraw';
	private static $table_log = 'core_withdraw_log';
	/** 用户提款未支付 */
	const WITHDRAW_STATE_NOT_PAID = 0;
	/** 用户提款已支付 */
	const WITHDRAW_STATE_PAID = 1;
	/** 用户提款已取消 */
	const WITHDRAW_STATE_PAID_CANCEL = -1;
	/** 用户提款被驳回并将提款金额再充值进游戏 */
	const WITHDRAW_STATE_REFUSED_BACKTOGAME = -2;
	/** 用户提款直接被拒绝 */
	const WITHDRAW_STATE_REFUSED = -3;
	/** 从游戏未提款 */
	const TRANSFER_STATE_FAILED = 0;
	/** 从游戏已提款 */
	const TRANSFER_STATE_SUCCESS = 1;
	/** 从游戏提款中 */
	const TRANSFER_STATE_PENDING = 2;
	
	public static $withdrawStates = Array(self::WITHDRAW_STATE_NOT_PAID=>'审核中', self::WITHDRAW_STATE_PAID=>'已确认',self::WITHDRAW_STATE_PAID_CANCEL=>'已取消',self::WITHDRAW_STATE_REFUSED_BACKTOGAME=>'拒绝后 退回平台',self::WITHDRAW_STATE_REFUSED=>'拒绝后 未退回平台');
	public static $transferStates = Array(self::TRANSFER_STATE_FAILED=>'平台转移失败', self::TRANSFER_STATE_SUCCESS=>'平台已转移', self::TRANSFER_STATE_PENDING=>'平台确认中');

	public static function getWithdrawState($state=''){
		if($state === ''){
		    return self::$withdrawStates;
		}
		return element($state, self::$withdrawStates, '');
	}
	public static function getTransferState($state=''){
		if($state === ''){
		    return self::$transferStates;
		}
		return element($state, self::$transferStates, '');
	}

	/**
	 * 取款记录请求
	 * @param string $user_id
	 * @param int $offset
	 */
	public static function getWithdrawList($user_id, $last_id){
		$db = IOSS_DB::getInstance();
		$db->select(array('id','amount as price','withdraw_status as status', 'FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%S") as time'));
		$db->from(self::$table);
		$db->where('user_id',$user_id);
		if($last_id){
			$db->where('id<',$last_id);
		}
		$db->order_by('id','DESC');
		$db->limit('8');
		$query = $db->get();
		return $query->result();
	}


	/**
	 * 创建余额提现记录
	 * @param string $user_id
	 * @param int $amount
	 * @param string $pay_channel
	 * @param string $transfer_platform
	 * @return boolean|IOSS_Order
	 */
	public static function create($user_id, $amount, $withdraw_bank_id, $transfer_platform){
		$db = IOSS_DB::getInstance();
		$time = time();
		$o['user_id'] = $user_id;
		$o['amount'] = $amount;
		$o['withdraw_status'] = self::WITHDRAW_STATE_NOT_PAID;
		$o['withdraw_time'] = $time;
		$o['withdraw_bank_id'] = $withdraw_bank_id;
		$o['withdraw_transaction'] = '';
		$o['transfer_platform'] = $transfer_platform;
		$o['transfer_status'] = self::TRANSFER_STATE_PENDING;
		$o['transfer_time'] = 0;
		$o['create_time'] = $time;
		$o['update_time'] = $time;
		$try_times = 0;
		do{
			if($try_times > 10){
				return  false; //重试次数太多，创建订单失败
			}
			$try_times ++;
			$o['no'] = date('ymdHis') . rand(1000, 9999);
			$unique = $db->get_where(self::$table, array('no' => $o['no']))->num_rows() === 0;
		}while($unique === false);
	
		if($db->insert(self::$table, $o)){
			$o['id'] =  $db->insert_id();
			return new self($o);
		}else{
			return false;
		}
	}
	
	/**
	 * 获取订单
	 * @param int $id
	 * @return Ambigous <NULL, IOSS_Order>
	 */
	public static function getById($id){
		$db = IOSS_DB::getInstance();
		$row = $db->where('id', $id)->get(self::$table)->row_array();
		return ($row == null) ? null : (new self($row));
	}
	
	/**
	 * 根据订单号获取订单
	 * @param string $no
	 * @return Ambigous <NULL, IOSS_Order>
	 */
	public static function getByNo($no){
		$db = IOSS_DB::getInstance();
		$row = $db->where('no', $no)->get(self::$table)->row_array();
		return ($row == null) ? null : (new self($row));
	}
	/**
	 * 获取订单列表
	 * @param array $where
	 * @param number $limit
	 * @return array<IOSS_Order>
	 */
	public static function getList($where, $limit = 10){
		$db = IOSS_DB::getInstance();
		$db->where($where);
		$db->order_by('id', 'desc');
		if($limit){
			$db->limit($limit);
		}
		$rows = $db->get(self::$table)->result_array();
		return array_map(function ($row){
			return new self($row);
		}, $rows);
	}
	
	
	private $order;
	
	private function __construct($row){
		$this->order = $row;
	}
	
	public function __get($key){
		return $this->order[$key];
	}
	
	/**
	 * 完成支付
	 * @param string $note
	 * @param string $transaction
	 * @return boolen
	 */
	public function pay($note = '', $transaction = ''){
		$db = IOSS_DB::getInstance();
		$time = time();
		$update['pay_status'] = self::WITHDRAW_STATE_PAID;
		$update['pay_time'] = $time;
		$update['pay_transaction'] = $transaction;
		$update['update_time'] = $time;
		$success = $db->where('id', $this->order['id'])->update(self::$table, $update) && ($db->affected_rows() >= 1);
		if($success ){
			$this->order = array_merge($this->order, $update);
			$this->log($note);
		}
		return $success;
	}
	
	/**
	 * 完成游戏内提款
	 * @param string $note
	 * @return boolen
	 */
	public function transfer($note = '',$credit=null,$name=null,$pass=null){
		$billno = date('ymdHis') . rand(1000,9999);
		if(!IOSS_AGApi::agin_prepare_transfer_credit($name,$pass,$billno,'OUT',$credit)){
			return false;
		}
		if(!IOSS_AGApi::agin_confirm_transfer_credit($name,$pass,$billno,'OUT',$credit,$error_message)){
			if($error_message['Type']!='network_error'){
				return false;
			}else{	//此时预转账成功、确认转账时info = network_error,需要调用 agin_query_transfer_status
				if(!IOSS_AGApi::agin_query_transfer_status($billno,$rec_error_message)){
					return false;
				}
			}
		}
		$db = IOSS_DB::getInstance();
		$time = time();
		$update['transfer_status'] = self::TRANSFER_STATE_SUCCESS;
		$update['transfer_time'] = $time;
		$update['update_time'] = $time;
		$success = $db->where('id', $this->order['id'])->update(self::$table, $update)  && ($db->affected_rows() >= 1);
		if($success){
			$this->order = array_merge($this->order, $update);
			$this->log($note);
		}
		return $success;
	}
	
	/**
	 * 添加订单日志
	 * @param string $note
	 */
	public function log($note){
		$db = IOSS_DB::getInstance();
		$log['withdraw_id'] = $this->order['id'];
		$log['withdraw_status'] =  $this->order['withdraw_status'];
		$log['transfer_status'] = $this->order['transfer_status'];
		$log['admin_id'] = 0;
		$log['admin_account'] = 'systme';
		$log['admin_name'] = '系统';
		$log['note'] = $note;
		$log['create_time'] = time();
		$db->insert(self::$table_log, $log);
	}
	
}